import WxRequest from 'wechat-request';

import { replaceProtocol, Logger } from '../utils/index'

let wxRequest = WxRequest
if(!wxRequest.defaults && wxRequest.default) {
    wxRequest = wxRequest.default
}

wxRequest.defaults.headers.post['Content-Type'] = 'application/json';
const logger = new Logger()
const host = 'https://wx.t.17u.cn'
const mobileApiHost = 'https://tcmobileapi.t.17usoft.com'

const successFn = (response) => {
    
    if(!response || response.status !== 200) {
        return
    }
    if(!response.data || response.data.Code !== 10000) {
        return
    }

    return response.data.Data   
}


export const requestAll = (promises) => {
    return wxRequest.all(promises)  
}

export const getCityLinesApi =  (params) => {
    return wxRequest.post(`${host}/shipapi/ShipLine/QueryCityLines`, params).then(response => successFn(response))
}

// 腾讯侧 openid和同程船票做绑定关系
export const tencentOpenIdConnectApi = (params) => {
    return wxRequest.post(`${host}/shipapi/WXMember/RelationShipAndTcentapplet`, params).then(response => successFn(response))
}

export const getMemberIdByOpenIdApi = (params) => {
    return wxRequest.get(`${mobileApiHost}/ship/ShipMini/ShipMiniQueryHandler.ashx?serviceName=getmemberidbyopenid&params=${encodeURIComponent(JSON.stringify(params))}`, )
}

export const getOpenIdByCodeApi = (params) => {
    return wxRequest.post(`${host}/shipapi/WXMember/GetOpenId`, params)
}

export const getUnionIdApi = (params) => {
    return wxRequest.post(`${host}/appapi/user/GetUserUnionId`, params)
}

export const getUserLoginInfoApi = (params) => {
    return wxRequest.post(`${host}/appapi/user/login/36`, params)
}


export const getLinesApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipVoyageApi/QueryVoyages`, params)
}

// 公告栏
export const getNoticeBoardApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipLine/GetShipNoticeBoard`, params)
}

// 班次详情 
export const getLineByVoyageNoApi = ({voyageSerialNo}) => {
    return wxRequest.get(`${host}/shipapi/ShipVoyageApi/QueryVoyageInfo?voyageSerialNo=${voyageSerialNo}`)
}

// 班次配置
export const getLineConfigApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipLine/QueryShipLineConfig`, params)

} 

export const getBookingNoteApi = ({lineId}) => {
    return wxRequest.get(`${host}/shipapi/ShipLine/QueryBookNotes?lineId=${lineId}`)
}

// 航线介绍新接口
export const newLineIntroductionApi = (params) => {
    return wxRequest.post(`${host}/shipapi/SightseeingBoat/GetBoatDescription`, params)
}

// 获取港口（通过港口航线ID查询） ShipLinePortApi/QueryShipCityLinePort
export const getCityLinePortApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipLinePortApi/QueryShipCityLinePort`, params)

}

// 彩页
export const getColorPageDataApi = (params) => {
    return wxRequest.post(`${host}/shipapi/SightseeingBoatColorPageApi/GetSightseeingBoatColorPage`, params)
}

export const getTripIntroductionApi = (params) => {
    const tabsList = [
        {
            title: '行程介绍',
            href: 'xingchengjieshaotab',
            content: ''
        },
        {
            title: '费用包含',
            href: 'feiyongbaohantab',
            content: ''
        }
    ]
    return wxRequest.post(`${host}/shipapi/ShipBoatApi/QueryShipTripInfo`, params).then((response) => {
        if(!response || response.status !== 200) {
            logger.warn('网络问题...')
            return
        }
        if(!response.data || response.data.Code !== 10000) {
            logger.warn('服务器问题..')
            return
        }
        const res = response.data.Data
        const tripIntroduction = res.TripExplain
        const tripFee = res.TripFee
        const pictureList = res.PictureLists
        let bannerList = [
            {
                src: '//file.40017.cn/ship/ship/images/ych_banner.jpg'
            }
        ]
        if (pictureList && pictureList.length > 0) {
            bannerList = pictureList.map(item => {
                return {
                    src: item
                }
            })
        }
        tabsList.forEach(item => {
            if (item.title === '行程介绍') {
                item.content = replaceProtocol(tripIntroduction)
            } else if (item.title === '费用包含') {
                item.content = replaceProtocol(tripFee)
            }
        })
        return {
            bannerList,
            tabsList
        }
    })
    .catch(error => {
        console.log(error)
    })
}
export const getBoatIntroductionApi = ({shipId}) => {

    const tabsList = [
        {
            title: '游船简介',
            href: 'youchuanjianjietab',
            content: ''
        },
        {
            title: '景点简介',
            href: 'jingdianjianjietab',
            content: ''
        },
        // {
        //     title: '港口地址',
        //     href: 'gangkoudizhitab',
        //     content: ''
        // }
    ]
    return wxRequest.get(`${host}/shipapi/ShipBoatApi/QueryShipBoat?shipId=${shipId}`).then((response) => {
        if(!response || response.status !== 200) {
            logger.warn('网络问题...')
            return
        }
        if(!response.data || response.data.Code !== 10000) {
            logger.warn('服务器问题..')
            return
        }
        const res = response.data.Data
        const rowBoat = res.Rowboat
        const rowBoatPicture = res.RowboatPicture
        let bannerList = [
            {
                src: '//file.40017.cn/ship/ship/images/ych_banner.jpg'
            }
        ]
        if (rowBoatPicture && rowBoatPicture.length > 0) {
            bannerList = rowBoatPicture.map(item => {
                return {
                    src: item
                }
            })
        }
        tabsList.forEach(item => {
            if (item.title === '游船简介') {
                item.content = replaceProtocol(rowBoat.BoatDesc)
            } else if (item.title === '景点简介') {
                item.content = replaceProtocol(rowBoat.ScenicDesc)
            }
        })
        return {
            bannerList,
            tabsList
        }
    })
    .catch(error => {
        console.log(error)
    })
}

// 货车配置
export const getTruckConfApi = ({method, supplierId, param}) => {
    return wxRequest.get(`${host}/shipapi/Bohailundu/Handle?method=${method}&supplierId=${supplierId}&param=${param}`).then(response => successFn(response))
}

export const getReserRuleApi = (params) => {
    return wxRequest.post(`${host}/shipapi/Reservation/GetReservationRule`, params)
}

// 获取保险配置
// 
export const getInsuranceConfigApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipInsurance/QueryInsuranceConfig`, params)
}

// 获取购票须知
export const getServiceNoticeApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipLine/LineServiceNotice`, params).then(response => successFn(response))
}

// 常旅配置
export const getChanlvConfigApi = ({LineId}) => {
    return wxRequest.get(`${host}/shipapi/LinkerApi/QueryLinkerConfig?lineId=${LineId}`).then(response => successFn(response))
}

// 常旅列表
export const getPassengersApi = (params) => {
    return wxRequest.post(`${host}/shipapi/LinkerApi/QueryLinker`, params).then(response => successFn(response))
}


// 乘客类型配置
export const getPassengerTypeConfApi = ({LineId}) => {
    return wxRequest.post(`${host}/shipapi/ShipLine/GePassengerTypeConfig?lineId=${LineId}`).then(response => successFn(response))
}

// 北海市民 校验接口 
export const checkBelongTypeApi = (params) => {
    return wxRequest.post(`${host}/shipapi/LinkerApi/JudgeBelongType`, params).then(response => successFn(response))
}

// 获取国籍列表
export const getNationalitiesApi = ({keyword}) => {
    return wxRequest.get(`${host}/shipapi/ShipCommonApi/QueryNationalitys?keyword=${keyword}`).then(response => successFn(response))
}


// 新增编辑常旅
export const createLinkerApi = (params) => {
    return wxRequest.post(`${host}/shipapi/LinkerApi/SaveLinker`, params)
}

// 删除常旅
export const deleteLinkerApi = (params) => {
    return wxRequest.post(`${host}/shipapi/LinkerApi/DeleteLinker`, params)
}

// 退改须知 
export const getRefundDescApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipLine/GetRefundDescription`, params).then(response => successFn(response))
}


// 下单
export const createOrderApi = (params) => {
    return wxRequest.post(`${mobileApiHost}/ship/WxApplet/ShipAppletOrderHandler.ashx`, params, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
}

// 飞机航线查询
export const getAirLinesApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipCommonAPi/QueryShipAirLine`, params).then(response => successFn(response))
}


// 非实名制 配置
export const getUnRealNameConfApi = ({lineId}) => {
    return wxRequest.get(`${host}/shipapi/ShipLine/QueryNonRealNameChangLvConfig?lineId=${lineId}`).then(response => successFn(response))
}

// 获取城市主题航线
export const getAllShipThemesApi = (params) => {
    return wxRequest.get(`${host}/shipapi/SightseeingBoatColorPageApi/GetAllShipTheme`, params)
}

// 首页专区
export const getShipZonesApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipZoneThemeApi/QueryShipZoneTheme`, params).then(response => successFn(response))
}


// 获取地址
export const getArddessApi = ({location, coord_type}) => {
    return wxRequest.get(`${host}/appapi/map/GetAddress?location=${location}&coord_type=${coord_type}`)
}


// 获取订单详情 by serialId
export const getOrderApi = ({ serialId }) => {
    return wxRequest.get(`${host}/shipapi/ShipOrderApi/QueryShipOrderDetail?serialId=${serialId}`).then(response => successFn(response))
}

// 退款进度 refundRecode
export const getRefundRecodeApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipOrderApi/RefundRecord`, params).then(response => successFn(response))
}

// 是否可退改
export const getCanRefundConfApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipRefund/CheckCanRefund`, params).then(response => successFn(response))
}

// 获取往返票优惠价格
export const getRoundTripDiscountPriceApi = (params) => {
    return wxRequest.post(`${host}/shipapi/ShipVoyageApi/QuerySeatDiscountPrice`, params).then(response => successFn(response))
}


// 接驳时间
export const verifyConnectTimeApi = function (params) {
    return wxRequest.post(`${host}/shipapi/ShipCommonAPi/VerifyConnectTime`, params).then(response => successFn(response))
}

// 证件识别
export const getScanCertificateApi = function(params) {
 
    return new Promise((resolve, reject) => {
        wx.uploadFile({
            // url: 'https://m.ly.com/shipapi/ShipCommonAPi/ScanCertificate',
            url: `${host}/shipapi/IdentityCardRecognition/Identity`,
            filePath: params.filePath,
            name: params.name,
            timeout: '10000',
            // formData: params.formData,
            success(res) {
                resolve(res)
            },
            fail(err) {
                reject(err)
            },
            complete: () => {
    
            }
        })
    })
}

// 发票详情 new
export const getInvoiceDetailNewApi = function ({supplierId, serialId}) {
    return wxRequest.get(`${host}/shipapi/Invoice/GetInvoiceDetailBySerialIdNew?supplierId=${supplierId}&serialId=${serialId}`)
}

// 反馈
export const feedBackApi = function (params) {
    return wxRequest.post(`${host}/shipapi/ShipCommonApi/RecordFeedBack`, params).then(response => successFn(response))
}

// 取消订单、预约单、收单
export const cancelShipOrderApi = function (params) {
    return wxRequest.post(`${host}/shipapi/ShipOrderApi/CancelShipOrder`, params)
}



// 发票抬头检索
export const getInvoiceTitleApi = function ({keyword}) {
    return wxRequest.get(`${host}/shipapi/api/GeneralPlatform?keyword=${keyword}`)
}


// 获取订单状态
export const getOrderStatusApi = function ({serialId}) {
    return wxRequest.get(`${host}/shipapi/ShipOrderApi/QueryOrderState?serialId=${serialId}`).then(response => successFn(response))
}


// 通知供应商出票
export const noticeSomeoneTicketOutApi = function ({serialId}) {
    return wxRequest.get(`${host}/shipapi/ShipOrderApi/NoticeSomeOneTicketOut?serialId=${serialId}`).then(response => successFn(response))
}


// 获取用户个人信息中的发票抬头
export const getInvoiceHistoryTitleApi = function ({id, channel, invoiceType}) {
    return wxRequest.get(`${host}/shipapi/Invoice/GetInvoiceTitle?id=${id}&channel=${channel}&invoiceType=${invoiceType}`)
}

// 申请开票新
export const invoiceDataChangeNewApi = function (params) {
    return wxRequest.post(`${host}/shipapi/Invoice/InvoiceDataChangeNew`, params)
}

// 退票
export const refundTicketApi = function (params) {
    return wxRequest.post(`${host}/shipapi/ShipRefund/ApplyRefund`, params)
}


// 出发和到达港口列表
export const departAndArrivePortsApi = function ({LineId}) {
    return wxRequest.get(`${host}/shipapi/ShipLinePortApi/QueryShipLinePort?LineId=${LineId}`).then(response => successFn(response))
}

// 地址
export const getLinePortsByIdApi = function ({lineId}) {
    return wxRequest.get(`${host}/shipapi/ShipLinePortApi/QueryShipLinePorts?lineId=${lineId}`).then(response => successFn(response))
}

// 获取省市区
export const queryRegionApi = function (params) {
    return wxRequest.post(`${host}/shipapi/ShipCommonApi/QueryStandardGlobalRegion`, params)
}


